package com.cgsd.heyu.utils;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;

import com.alipay.sdk.app.PayTask;
import com.android.library.utils.LogUtils;
import com.cgsd.heyu.entity.PayResult;

import java.util.Map;

/**
 * Author: sky on 2021/3/8 15:10
 * Email: xcode126@126.com
 * Desc:
 */
public class ALiPayUtil {

    public static final String PAY_SUCCESS = "9000";
    private Activity context;
    private String aliPayStr;

    public ALiPayUtil(Activity context, String aliPayStr, PayResultListener listener) {
        this.context = context;
        this.aliPayStr = aliPayStr;
        this.listener = listener;
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private Runnable payRunnable = new Runnable() {
        @Override
        public void run() {
            PayTask alipay = new PayTask(context);
            Map<String, String> result = alipay.payV2(aliPayStr, true);
            Log.i("==>", result.toString());
            Message msg = new Message();
            msg.what = 100;
            msg.obj = result;
            mHandler.sendMessage(msg);
        }
    };

    private Handler mHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            LogUtils.d("print", payResult.getResult());
            LogUtils.d("print", payResult.toString());
            if (listener != null) {
                listener.onPayResult(PAY_SUCCESS.equals(payResult.getResultStatus()));
            }
//            if (PAY_SUCCESS.equals(payResult.getResultStatus())) {
//                //支付成功
////                showPaySuccessDialog();
////                mPresenter.getUserInfo();
//                if (listener != null) {
//                    listener.PayResult();
//                }
//            } else {
//                if (listener != null) {
//                    listener.PayResult();
//                }
//                //支付失败
//                showToast("支付失败");
//            }
            return false;
        }
    });


    public PayResultListener listener;

    public interface PayResultListener {
        void onPayResult(boolean isSuccess);
    }

    /**
     * 检测是否安装支付宝
     * @param context
     * @return
     */
    public static boolean isAliPayInstalled(Context context) {
        Uri uri = Uri.parse("alipays://platformapi/startApp");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        ComponentName componentName = intent.resolveActivity(context.getPackageManager());
        return componentName != null;
    }

}
